package com.odobenus.client.zk;

import org.I0Itec.zkclient.ZkClient;
import org.apache.zookeeper.CreateMode;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 基于 ZooKeeper 的客戶端注册实现
 */
public class ZooKeeperServiceRegistry  {

    private static final Logger LOGGER = LoggerFactory.getLogger(ZooKeeperServiceRegistry.class);

    private final ZkClient zkClient;
    public ZooKeeperServiceRegistry(String zkAddress) {
    	zkClient = new ZkClient(zkAddress, Constant.ZK_SESSION_TIMEOUT, Constant.ZK_CONNECTION_TIMEOUT);
    	LOGGER.info("connect zookeeper");
    	if (!zkClient.exists(Constant.ZK_REGISTRY_PATH)) {
			zkClient.create(Constant.ZK_REGISTRY_PATH, "0",CreateMode.PERSISTENT);
		}
    }

    public void register(String clientName,String clientAddress) {
		try {
			String addressPath = Constant.ZK_REGISTRY_PATH + "/" + clientName + Constant.ZK_SPLIT_CHAR+ clientAddress;//项目名/接口调用地址
			if (!zkClient.exists(addressPath)) {
				String res = zkClient.create(addressPath, "0",CreateMode.EPHEMERAL);
				LOGGER.info(clientName+" 注册成功 " + res);
			}else {
				throw new RuntimeException("注册名-地址【"+addressPath+"】已存在，请更换!");
			}
			
		} catch (Exception e) {
			e.printStackTrace();
		}
    }
}